import 'dart:io';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart' as getx;
import 'package:device_info_plus/device_info_plus.dart';
import 'storage_service.dart';
import 'user_service.dart';
import 'app_config_service.dart';
import '../models/index.dart';
import '../values/constants.dart';

/// Dio网络服务 - 基础设施层
/// 负责应用的HTTP网络请求，基于 Dio 库
/// 
/// 🎯 核心职责：
/// - 提供标准的HTTP请求能力 (GET, POST, PUT, DELETE等)
/// - 统一的请求/响应拦截器管理
/// - 自动错误处理和重试机制
/// - 请求取消和超时控制
/// - 文件上传/下载支持
/// 
/// ⚠️ 设计原则：
/// - 只负责网络请求，不包含具体业务逻辑
/// - 不应该知道具体的API业务概念
/// - 业务API应该在对应的业务服务中定义
class DioService extends getx.GetxService {
  static DioService get to => getx.Get.find<DioService>();
  
  late Dio _dio;
  
  // 响应式状态变量
  final _isInitialized = false.obs;
  final _isOnline = true.obs;
  
  // Getters - 同步访问
  bool get isInitialized => _isInitialized.value;
  bool get isOnline => _isOnline.value;
  Dio get dio => _dio;
  
  // Getters - 响应式访问
  getx.RxBool get isInitializedRx => _isInitialized;
  getx.RxBool get isOnlineRx => _isOnline;
  
  @override
  Future<void> onInit() async {
    super.onInit();
    debugPrint('🌐 DioService 初始化开始...');
    
    try {
      await _initDio();
      _setupInterceptors();
      await _checkNetworkStatus();
      _isInitialized.value = true;
      
      debugPrint('✅ DioService 初始化完成');
    } catch (e) {
      debugPrint('❌ DioService 初始化失败: $e');
      rethrow;
    }
  }
  
  /// 初始化 Dio 实例
  Future<void> _initDio() async {
    try {
      final baseOptions = BaseOptions(
        connectTimeout: const Duration(milliseconds: Constants.defaultConnectTimeout),
        receiveTimeout: const Duration(milliseconds: Constants.defaultReceiveTimeout),
        sendTimeout: const Duration(milliseconds: Constants.defaultSendTimeout),
        headers: {
          Constants.httpHeaderContentType: Constants.httpContentTypeJson,
          Constants.httpHeaderAccept: Constants.httpAcceptJson,
          Constants.httpHeaderUserAgent: Constants.defaultUserAgent,
        },
        // 设置API服务器的基础URL
        baseUrl: Constants.apiBaseUrl,
        validateStatus: (status) {
          // 接受所有状态码，由拦截器统一处理
          return status != null && status < Constants.httpStatusMaxValid;
        },
      );
      
      _dio = Dio(baseOptions);
      
      // 配置SSL证书处理（仅在debug模式下跳过证书验证）
      if (kDebugMode) {
        _configureDevelopmentSSL();
      }
      
      debugPrint('📡 Dio 实例创建成功');
    } catch (e) {
      debugPrint('❌ Dio 实例创建失败: $e');
      rethrow;
    }
  }
  
  /// 配置开发环境SSL证书处理
  void _configureDevelopmentSSL() {
    try {
      (_dio.httpClientAdapter as IOHttpClientAdapter).createHttpClient = () {
        final client = HttpClient();
        
        // 在开发环境中跳过SSL证书验证
        client.badCertificateCallback = (X509Certificate cert, String host, int port) {
          debugPrint('🔓 跳过SSL证书验证: $host:$port (开发环境)');
          return true; // 在开发环境中接受所有证书
        };
        
        return client;
      };
      
      debugPrint('🔓 已配置开发环境SSL证书跳过验证');
    } catch (e) {
      debugPrint('⚠️ SSL配置失败: $e');
    }
  }
  
  /// 设置拦截器
  void _setupInterceptors() {
    // 1. 请求拦截器 - 添加通用请求头
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        debugPrint('🔄 请求开始: ${options.method} ${options.uri}');
        
        // 主动检查并刷新token（企业级最佳实践）
        final shouldContinue = await _checkAndRefreshTokenBeforeRequest(options);
        if (!shouldContinue) {
          // Token刷新失败，取消请求
          final error = DioException(
            requestOptions: options,
            response: null,
            type: DioExceptionType.cancel,
            error: 'Token刷新失败，请重新登录',
          );
          handler.reject(error);
          return;
        }
        
        // 🔥 添加 Android 原生 API 必需的公共参数
        await _addNativeCommonParams(options);
        
        // 自动添加认证token（可能已经在上面被更新）
        _addAuthToken(options);
        
        // 添加请求ID用于追踪
        final requestId = DateTime.now().millisecondsSinceEpoch.toString();
        options.headers[Constants.httpHeaderRequestId] = requestId;
        
        // 在debug模式下打印请求详情
        if (kDebugMode) {
          debugPrint('📤 请求头: ${options.headers}');
          if (options.data != null) {
            debugPrint('📤 请求数据: ${options.data}');
          }
        }
        
        handler.next(options);
      },
      onResponse: (response, handler) {
        debugPrint('✅ 请求成功: ${response.statusCode} ${response.requestOptions.uri}');
        
        // 在debug模式下打印响应详情
        if (kDebugMode) {
          debugPrint('📥 响应数据: ${response.data}');
        }
        
        handler.next(response);
      },
      onError: (DioException error, handler) async {
        debugPrint('❌ 请求失败: ${error.requestOptions.method} ${error.requestOptions.uri}');
        debugPrint('❌ 错误信息: ${error.message}');
        debugPrint('❌ 错误类型: ${error.type}');
        
        // 检查是否是401错误且可以尝试刷新令牌
        if (error.response?.statusCode == Constants.httpStatusUnauthorized) {
          debugPrint('🔄 检测到401错误，响应数据: ${error.response?.data}');
          
          final shouldTryRefresh = await _shouldTryRefreshToken(error.requestOptions);
          debugPrint('🔄 是否应该尝试刷新令牌: $shouldTryRefresh');
          
          if (shouldTryRefresh) {
            debugPrint('🔄 开始尝试刷新令牌并重试原请求...');
            
            try {
              // 尝试刷新令牌
              final refreshResult = await _tryRefreshTokenAndRetry(error.requestOptions);
              
              if (refreshResult != null) {
                debugPrint('✅ 令牌刷新成功，重新发送原请求完成');
                handler.resolve(refreshResult);
                return;
              } else {
                debugPrint('❌ 刷新令牌后重试失败，继续原错误处理流程');
              }
            } catch (e) {
              debugPrint('❌ 刷新令牌过程中发生异常: $e');
            }
          } else {
            debugPrint('⚠️ 不满足刷新令牌条件，继续原错误处理流程');
          }
        }
        
        // 如果不是401错误或刷新令牌失败，继续原有的错误处理流程
        final networkException = _processError(error);
        
        // 重新包装为DioException，但使用自定义异常作为error
        final processedError = DioException(
          requestOptions: error.requestOptions,
          response: error.response,
          type: error.type,
          error: networkException,
        );
        
        handler.next(processedError);
      },
    ));
    
    // 2. 日志拦截器 (仅在debug模式下)
    if (kDebugMode) {
      _dio.interceptors.add(LogInterceptor(
        requestBody: true,
        responseBody: true,
        requestHeader: false,
        responseHeader: false,
        error: true,
      ));
    }
    
    debugPrint('🔧 网络拦截器设置完成');
  }
  
  /// 自动添加认证token
  /// 添加 Android 原生 API 必需的公共参数
  /// 
  /// 对标 Android 原生 HttpClient.getInstance().post() 的参数添加逻辑
  /// 所有请求必须包含：_uid_, _token_, _OS_, _OSV_, _OSInfo_
  Future<void> _addNativeCommonParams(RequestOptions options) async {
    try {
      // 获取用户ID和token
      int uid = 0;
      String token = '';
      
      try {
        final userService = getx.Get.find<UserService>();
        // 🔥 修复1：从 currentUserProfile 获取 userId
        uid = userService.currentUserProfile?.userId ?? 0;
        // 🔥 修复2：userToken 本身就是 String，不需要 .value
        token = userService.userToken;
      } catch (e) {
        debugPrint('⚠️ 无法获取UserService: $e');
      }
      
      // 如果UserService不可用，尝试从存储获取
      if (uid == 0 || token.isEmpty) {
        final storageService = getx.Get.find<StorageService>();
        uid = storageService.getInt(Constants.storageKeyUserId) ?? 0;
        token = storageService.getString(Constants.storageKeyUserToken) ?? '';
      }
      
      // 🔥 修复3：获取真实的操作系统版本（对标Android原生Build.VERSION.RELEASE）
      final osType = Platform.isIOS ? 'ios' : 'android';
      String osVersion = '';
      
      try {
        final deviceInfo = DeviceInfoPlugin();
        if (Platform.isIOS) {
          final iosInfo = await deviceInfo.iosInfo;
          // iOS系统版本，如"17.2"
          osVersion = iosInfo.systemVersion;
          debugPrint('📱 iOS系统版本: $osVersion (来自systemVersion)');
        } else if (Platform.isAndroid) {
          final androidInfo = await deviceInfo.androidInfo;
          // Android系统版本，如"11"、"12"（对应Android原生的Build.VERSION.RELEASE）
          osVersion = androidInfo.version.release;
          debugPrint('📱 Android系统版本: $osVersion (来自version.release)');
        }
      } catch (e) {
        debugPrint('⚠️ 无法获取操作系统版本: $e');
        osVersion = '';
      }
      
      final osInfo = ''; // Android 原生返回空字符串
      
      // 🔥 关键修复：将参数添加到请求体（POST）或查询参数（GET）
      final params = {
        '_uid_': uid.toString(),
        '_token_': token,
        '_OS_': osType,
        '_OSV_': osVersion,
        '_OSInfo_': osInfo,
      };
      
      if (options.method == 'POST' || options.method == 'PUT' || options.method == 'PATCH') {
        // POST/PUT/PATCH 请求：添加到请求体
        if (options.data is Map) {
          final Map<String, dynamic> data = Map.from(options.data as Map);
          data.addAll(params);
          options.data = data;
        } else if (options.data == null) {
          options.data = params;
        }
        debugPrint('🔧 已添加Android原生公共参数到POST请求体');
      } else {
        // GET 请求：添加到查询参数
        options.queryParameters.addAll(params);
        debugPrint('🔧 已添加Android原生公共参数到GET查询参数');
      }
      
      if (kDebugMode) {
        final tokenPreview = token.isNotEmpty && token.length > 10 
            ? '${token.substring(0, 10)}...' 
            : token;
        debugPrint('📱 原生公共参数: uid=$uid, token=$tokenPreview, OS=$osType, OSV=$osVersion');
      }
    } catch (e) {
      debugPrint('⚠️ 添加原生公共参数失败: $e');
      // 不抛出异常，继续请求
    }
  }
  
  void _addAuthToken(RequestOptions options) {
    try {
      // 检查当前API是否在白名单中（不需要token）
      if (_isNoAuthRequired(options.path)) {
        debugPrint('🔓 API在白名单中，跳过添加token: ${options.path}');
        return;
      }
      
      String? userToken;
      
      // 优先从UserService获取当前token（支持临时token）
      try {
        final userService = getx.Get.find<UserService>();
        if (userService.userToken.isNotEmpty) {
          userToken = userService.userToken;
          debugPrint('🔐 从UserService获取token');
        }
      } catch (e) {
        debugPrint('⚠️ UserService不可用: $e');
      }
      
      // 如果UserService没有token，从存储服务获取
      if (userToken == null || userToken.isEmpty) {
        final storageService = getx.Get.find<StorageService>();
        userToken = storageService.getString(Constants.storageKeyUserToken);
        if (userToken != null && userToken.isNotEmpty) {
          debugPrint('🔐 从存储服务获取token');
        }
      }
      
      if (userToken != null && userToken.isNotEmpty) {
        options.headers[Constants.httpHeaderAuthorization] = '${Constants.httpBearerPrefix}$userToken';
        debugPrint('🔐 已添加认证token');
      }
    } catch (e) {
      debugPrint('⚠️ 获取用户token失败: $e');
      // 不抛出异常，继续请求
    }
  }
  
  /// 检查API路径是否不需要认证token
  bool _isNoAuthRequired(String path) {
    for (final noAuthPath in Constants.noAuthRequiredPaths) {
      // 如果是以'/'结尾的路径，表示前缀匹配
      if (noAuthPath.endsWith('/')) {
        if (path.startsWith(noAuthPath)) {
          return true;
        }
      } else {
        // 精确匹配
        if (path == noAuthPath) {
          return true;
        }
      }
    }
    return false;
  }
  
  /// 检查API路径是否不需要认证token（公开方法）
  bool isNoAuthRequired(String path) {
    return _isNoAuthRequired(path);
  }
  
  /// 处理网络错误，转换为自定义异常模型
  NetworkExceptionModel _processError(DioException error) {
    final requestPath = error.requestOptions.path;
    final requestMethod = error.requestOptions.method;
    
    switch (error.type) {
      case DioExceptionType.connectionTimeout:
        _isOnline.value = false;
        return NetworkExceptionModel.connectionTimeout(
          requestPath: requestPath,
          requestMethod: requestMethod,
          originalException: error,
        );
        
      case DioExceptionType.sendTimeout:
        return NetworkExceptionModel.requestTimeout(
          requestPath: requestPath,
          requestMethod: requestMethod,
          originalException: error,
        );
        
      case DioExceptionType.receiveTimeout:
        return NetworkExceptionModel.requestTimeout(
          requestPath: requestPath,
          requestMethod: requestMethod,
          originalException: error,
        );
        
      case DioExceptionType.badResponse:
        return _handleHttpError(error.response, requestPath, requestMethod, error);
        
      case DioExceptionType.cancel:
        return NetworkExceptionModel.cancelled(
          requestPath: requestPath,
          requestMethod: requestMethod,
          originalException: error,
        );
        
      case DioExceptionType.connectionError:
        _isOnline.value = false;
        return NetworkExceptionModel.connectionError(
          requestPath: requestPath,
          requestMethod: requestMethod,
          originalException: error,
        );
        
      case DioExceptionType.badCertificate:
        return NetworkExceptionModel(
          code: Constants.errorCodeSsl,
          message: 'SSL证书验证失败',
          type: NetworkErrorType.network,
          requestPath: requestPath,
          requestMethod: requestMethod,
          originalException: error,
        );
        
      case DioExceptionType.unknown:
        return NetworkExceptionModel.unknown(
          message: '未知网络错误: ${error.message}',
          requestPath: requestPath,
          requestMethod: requestMethod,
          originalException: error,
        );
    }
  }
  
  /// 处理HTTP状态码错误
  NetworkExceptionModel _handleHttpError(
    Response? response,
    String? requestPath,
    String? requestMethod,
    DioException originalException,
  ) {
    if (response == null) {
      return NetworkExceptionModel.serverError(
        requestPath: requestPath,
        requestMethod: requestMethod,
        originalException: originalException,
      );
    }
    
    final statusCode = response.statusCode ?? 0;
    
    // 使用工厂方法创建特定类型的异常
    switch (statusCode) {
      case 401:
        return NetworkExceptionModel.unauthorized(
          requestPath: requestPath,
          requestMethod: requestMethod,
          originalException: originalException,
        );
        
      case 403:
        return NetworkExceptionModel.forbidden(
          requestPath: requestPath,
          requestMethod: requestMethod,
          originalException: originalException,
        );
        
      case 404:
        return NetworkExceptionModel.notFound(
          requestPath: requestPath,
          requestMethod: requestMethod,
          originalException: originalException,
        );
        
      default:
        // 对于其他HTTP状态码，使用通用的httpError工厂方法
        return NetworkExceptionModel.httpError(
          statusCode: statusCode,
          requestPath: requestPath,
          requestMethod: requestMethod,
          originalException: originalException,
        );
    }
  }
  
  /// 检查网络状态
  Future<void> _checkNetworkStatus() async {
    try {
      // 简单的网络检查，ping Google DNS
      await InternetAddress.lookup(Constants.googleDns);
      _isOnline.value = true;
      debugPrint('🌐 网络连接正常');
    } catch (e) {
      _isOnline.value = false;
      debugPrint('📶 网络连接异常: $e');
    }
  }
  
  // ==================== 公共HTTP方法 ====================
  
  /// GET请求
  Future<Response<T>> get<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onReceiveProgress,
  }) async {
    try {
      return await _dio.get<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
        onReceiveProgress: onReceiveProgress,
      );
    } catch (e) {
      debugPrint('❌ GET请求失败: $path - $e');
      rethrow;
    }
  }
  
  /// POST请求
  Future<Response<T>> post<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  }) async {
    try {
      return await _dio.post<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
        onSendProgress: onSendProgress,
        onReceiveProgress: onReceiveProgress,
      );
    } catch (e) {
      debugPrint('❌ POST请求失败: $path - $e');
      rethrow;
    }
  }
  
  /// PUT请求
  Future<Response<T>> put<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  }) async {
    try {
      return await _dio.put<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
        onSendProgress: onSendProgress,
        onReceiveProgress: onReceiveProgress,
      );
    } catch (e) {
      debugPrint('❌ PUT请求失败: $path - $e');
      rethrow;
    }
  }
  
  /// DELETE请求
  Future<Response<T>> delete<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    try {
      return await _dio.delete<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
      );
    } catch (e) {
      debugPrint('❌ DELETE请求失败: $path - $e');
      rethrow;
    }
  }
  
  /// PATCH请求
  Future<Response<T>> patch<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  }) async {
    try {
      return await _dio.patch<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
        cancelToken: cancelToken,
        onSendProgress: onSendProgress,
        onReceiveProgress: onReceiveProgress,
      );
    } catch (e) {
      debugPrint('❌ PATCH请求失败: $path - $e');
      rethrow;
    }
  }
  
  // ==================== 文件操作方法 ====================
  
  /// 下载文件
  Future<Response> downloadFile(
    String url,
    String savePath, {
    ProgressCallback? onReceiveProgress,
    CancelToken? cancelToken,
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) async {
    try {
      debugPrint('📥 开始下载文件: $url -> $savePath');
      
      return await _dio.download(
        url,
        savePath,
        onReceiveProgress: onReceiveProgress,
        cancelToken: cancelToken,
        queryParameters: queryParameters,
        options: options,
      );
    } catch (e) {
      debugPrint('❌ 文件下载失败: $url - $e');
      rethrow;
    }
  }
  
  /// 上传文件
  Future<Response<T>> uploadFile<T>(
    String path,
    String filePath, {
    String? fileName,
    String fileKey = 'file',
    Map<String, dynamic>? data,
    ProgressCallback? onSendProgress,
    CancelToken? cancelToken,
  }) async {
    try {
      debugPrint('📤 开始上传文件: $filePath -> $path');
      
      final formData = FormData.fromMap({
        ...?data,
        fileKey: await MultipartFile.fromFile(
          filePath,
          filename: fileName,
        ),
      });
      
      return await post<T>(
        path,
        data: formData,
        cancelToken: cancelToken,
        onSendProgress: onSendProgress,
      );
    } catch (e) {
      debugPrint('❌ 文件上传失败: $filePath - $e');
      rethrow;
    }
  }
  
  /// 上传多个文件
  Future<Response<T>> uploadMultipleFiles<T>(
    String path,
    List<String> filePaths, {
    String fileKey = 'files',
    Map<String, dynamic>? data,
    ProgressCallback? onSendProgress,
    CancelToken? cancelToken,
  }) async {
    try {
      debugPrint('📤 开始上传多个文件: ${filePaths.length}个文件 -> $path');
      
      final files = <MultipartFile>[];
      for (String filePath in filePaths) {
        files.add(await MultipartFile.fromFile(filePath));
      }
      
      final formData = FormData.fromMap({
        ...?data,
        fileKey: files,
      });
      
      return await post<T>(
        path,
        data: formData,
        cancelToken: cancelToken,
        onSendProgress: onSendProgress,
      );
    } catch (e) {
      debugPrint('❌ 多文件上传失败: $e');
      rethrow;
    }
  }
  
  // ==================== 工具方法 ====================
  
  /// 设置Base URL
  void setBaseUrl(String baseUrl) {
    _dio.options.baseUrl = baseUrl;
    debugPrint('🔧 设置Base URL: $baseUrl');
  }
  
  /// 添加公共请求头
  void addHeaders(Map<String, dynamic> headers) {
    _dio.options.headers.addAll(headers);
    debugPrint('🔧 添加公共请求头: $headers');
  }
  
  /// 移除请求头
  void removeHeader(String key) {
    _dio.options.headers.remove(key);
    debugPrint('🔧 移除请求头: $key');
  }
  
  /// 设置超时时间
  void setTimeout({
    Duration? connectTimeout,
    Duration? receiveTimeout,
    Duration? sendTimeout,
  }) {
    if (connectTimeout != null) {
      _dio.options.connectTimeout = connectTimeout;
    }
    if (receiveTimeout != null) {
      _dio.options.receiveTimeout = receiveTimeout;
    }
    if (sendTimeout != null) {
      _dio.options.sendTimeout = sendTimeout;
    }
    debugPrint('🔧 设置超时时间: connect=$connectTimeout, receive=$receiveTimeout, send=$sendTimeout');
  }
  
  /// 添加拦截器
  void addInterceptor(Interceptor interceptor) {
    _dio.interceptors.add(interceptor);
    debugPrint('🔧 添加拦截器: ${interceptor.runtimeType}');
  }
  
  /// 移除拦截器
  void removeInterceptor(Interceptor interceptor) {
    _dio.interceptors.remove(interceptor);
    debugPrint('🔧 移除拦截器: ${interceptor.runtimeType}');
  }
  
  /// 清除所有拦截器
  void clearInterceptors() {
    _dio.interceptors.clear();
    debugPrint('🔧 清除所有拦截器');
  }
  
  /// 创建取消token
  CancelToken createCancelToken() {
    return CancelToken();
  }
  
  /// 重新检查网络状态
  Future<void> checkNetworkStatus() async {
    await _checkNetworkStatus();
  }
  
  // ==================== 令牌刷新相关方法 ====================
  
  /// 在发送请求前主动检查并刷新token（企业级最佳实践）
  Future<bool> _checkAndRefreshTokenBeforeRequest(RequestOptions requestOptions) async {
    try {
      debugPrint('🔍 主动检查token状态...');
      
      // 如果是不需要token的API，跳过检查
      if (_isNoAuthRequired(requestOptions.path)) {
        debugPrint('🔓 API在白名单中，跳过token检查: ${requestOptions.path}');
        return true;
      }
      
      // 如果是刷新token的请求，不进行检查（避免无限循环）
      if (requestOptions.path.contains(Constants.apiPathRefreshPattern)) {
        debugPrint('⚠️ 这是刷新token请求，跳过检查');
        return true;
      }
      
      // 获取UserService检查token状态
      final userService = getx.Get.find<UserService>();
      if (!userService.isLoggedIn || userService.userToken.isEmpty) {
        debugPrint('⚠️ 用户未登录或token为空，跳过token检查');
        return true;
      }
      
      // 获取当前token模型
      final currentToken = _getCurrentTokenModel();
      if (currentToken == null) {
        debugPrint('⚠️ 无法获取当前token模型，跳过检查');
        return true;
      }
      
      debugPrint('🔍 Token状态检查: 剩余${currentToken.remainingExpiresIn}秒, 已过期:${currentToken.isExpired}, 即将过期:${currentToken.isExpiringSoon()}');
      
      // 如果token已过期或即将在1分钟内过期，主动刷新
      if (currentToken.isExpired || currentToken.isExpiringSoon()) {
        debugPrint('🔄 Token已过期或即将过期，主动刷新...');
        
        final refreshResult = await userService.refreshAccessToken();
        if (refreshResult.isSuccess) {
          debugPrint('✅ 主动刷新token成功');
          return true;
        } else {
          debugPrint('❌ 主动刷新token失败: ${refreshResult.errorMessage}');
          return false;
        }
      } else {
        debugPrint('✅ Token状态良好，继续请求');
        return true;
      }
      
    } catch (e) {
      debugPrint('❌ 主动检查token异常: $e');
      // 异常情况下继续请求，让后续的401处理机制兜底
      return true;
    }
  }
  
  /// 获取当前token模型
  TokenModel? _getCurrentTokenModel() {
    try {
      final userService = getx.Get.find<UserService>();
      
      // 首先尝试获取完整的TokenModel
      final tokenModel = userService.getTokenModel();
      if (tokenModel != null) {
        return tokenModel;
      }
      
      // 如果没有存储完整的token模型，尝试从基本信息构建（向后兼容）
      if (userService.userToken.isNotEmpty) {
        debugPrint('⚠️ 使用临时TokenModel，建议重新登录以获得准确的过期时间');
        return TokenModel(
          accessToken: userService.userToken,
          expiresIn: Constants.defaultAccessTokenExpiresIn, // 默认1小时，不准确
          refreshToken: userService.refreshToken,
          refreshExpiresIn: Constants.defaultRefreshTokenExpiresIn, // 默认1天，不准确
          obtainedAt: DateTime.now().millisecondsSinceEpoch - Constants.fallbackTokenObtainedOffset, // 假设获取时间，不准确
        );
      }
      
      return null;
    } catch (e) {
      debugPrint('❌ 获取当前token模型失败: $e');
      return null;
    }
  }
  
  /// 检查是否应该尝试刷新令牌
  Future<bool> _shouldTryRefreshToken(RequestOptions requestOptions) async {
    debugPrint('🔍 检查是否应该尝试刷新令牌...');
    debugPrint('🔍 请求路径: ${requestOptions.path}');
    debugPrint('🔍 请求额外信息: ${requestOptions.extra}');
    
    // 如果是不需要token的API，不需要刷新令牌
    if (_isNoAuthRequired(requestOptions.path)) {
      debugPrint('🔓 API在白名单中，不需要刷新令牌: ${requestOptions.path}');
      return false;
    }
    
    // 检查请求是否已经是重试过的（避免无限循环）
    if (requestOptions.extra.containsKey('_is_retry')) {
      debugPrint('⚠️ 请求已经是重试过的，跳过令牌刷新');
      return false;
    }
    
    // 检查是否是刷新令牌的请求本身（避免无限循环）
    if (requestOptions.path.contains(Constants.apiPathRefreshPattern)) {
      debugPrint('⚠️ 这是刷新令牌请求本身，跳过自动刷新');
      return false;
    }
    
    // 检查是否有UserService可用
    try {
      final userService = getx.Get.find<UserService>();
      debugPrint('🔍 UserService找到，当前刷新令牌长度: ${userService.refreshToken.length}');
      
      // 检查是否有有效的刷新令牌
      if (userService.refreshToken.isEmpty) {
        debugPrint('⚠️ 没有有效的刷新令牌，跳过自动刷新');
        return false;
      }
      
      debugPrint('✅ 满足刷新令牌条件，可以尝试刷新');
      return true;
    } catch (e) {
      debugPrint('⚠️ UserService不可用，跳过令牌刷新: $e');
      return false;
    }
  }
  
  /// 尝试刷新令牌并重新发送请求
  Future<Response?> _tryRefreshTokenAndRetry(RequestOptions originalRequestOptions) async {
    try {
      debugPrint('🔄 开始尝试刷新令牌并重试请求');
      
      // 获取UserService实例
      final userService = getx.Get.find<UserService>();
      debugPrint('🔄 UserService获取成功，准备调用refreshAccessToken');
      
      // 尝试刷新令牌
      final refreshResult = await userService.refreshAccessToken();
      debugPrint('🔄 刷新令牌API调用完成，结果: ${refreshResult.isSuccess}');
      
      if (refreshResult.isSuccess && refreshResult.tokenModel != null) {
        debugPrint('✅ 令牌刷新成功，准备重新发送原请求');
        debugPrint('🔑 新访问令牌长度: ${refreshResult.tokenModel!.accessToken.length}');
        
        // 更新原请求的Authorization头
        final newToken = refreshResult.tokenModel!.accessToken;
        originalRequestOptions.headers[Constants.httpHeaderAuthorization] = '${Constants.httpBearerPrefix}$newToken';
        
        // 标记这是一个重试请求，避免无限循环
        originalRequestOptions.extra['_is_retry'] = true;
        
        debugPrint('🔄 准备重新发送原请求: ${originalRequestOptions.method} ${originalRequestOptions.uri}');
        
        // 重新发送原请求
        final retryResponse = await _dio.fetch(originalRequestOptions);
        debugPrint('✅ 重试请求完成，状态码: ${retryResponse.statusCode}');
        
        return retryResponse;
      } else {
        debugPrint('❌ 令牌刷新失败: ${refreshResult.errorMessage}');
        return null;
      }
    } catch (e) {
      debugPrint('❌ 刷新令牌过程中发生异常: $e');
      debugPrint('❌ 异常堆栈: ${StackTrace.current}');
      return null;
    }
  }
  
  @override
  void onClose() {
    debugPrint('🧹 DioService 正在清理...');
    _dio.close();
    super.onClose();
  }
}
